package com.bdqn.service;

import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.bdqn.config.mybatis.ServiceImpl;
import com.bdqn.mapper.UserMapper;
import com.bdqn.pojo.User;


import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

/**
 * @author LILIBO
 * @description 针对表【sys_user】的数据库操作Service实现
 * @createDate 2022-11-30 11:01:02
 */
@Service("UserService")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;


    /**
     * 通过用户特征查找用户
     *
     * @param user
     * @return
     */
    @Override
    public User getUser(User user) {
        return userMapper.getUser(user);
    }

    /**
     * 用户登录
     *
     * @param usrName
     * @param usrPassword
     * @return
     */
    @Override
    public User login(String usrName, String usrPassword) {
        if (StringUtils.isEmpty(usrName) || StringUtils.isEmpty(usrPassword)) {
            return null;
        }
        // 将原始密码加密
        String enPassword = encryptPassword(usrPassword);
        User param = new User();
        param.setUsrName(usrName);
        param.setUsrPassword(enPassword);
        return this.getUser(param);
    }

    @Override
    public String save(String password) {

        return encryptPassword(password);
    }

    /**
     * 使用MD5加密方式
     * 1、不可逆加密（只能加密，不能解密）
     * 2、相同的明文一定加密为相同的密文
     * 3、不同的明文一定加密为不同的密文
     *
     * @param plaintextPassword
     * @return
     * @throws IllegalArgumentException
     */
    public static String encryptPassword(String plaintextPassword) throws IllegalArgumentException {
        String salt = "czkt"; // 盐值
        MD5 md5 = new MD5();
        int length = plaintextPassword.getBytes(StandardCharsets.UTF_8).length;
        length = length % 3 + 3;
        md5.setSalt(salt.getBytes(StandardCharsets.UTF_8));
        String enPassword = plaintextPassword;
        for (int i = 0; i < length; i++) {
            enPassword = md5.digestHex(enPassword);
        }
        return enPassword;
    }

}